package com.umfwechat.h5.controller.cashier;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CacheConsts;
import com.umfwechat.util.RedisUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.StringUtil;
import com.umfwechat.wx.service.WeixinService;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.service.sys.remote.UserServiceRemote;
import com.umpay.sp.util.ConstEC;
import com.umpay.sp.xml.XmlData;

/**
 * @ClassName CashierController
 * @desc 收银员列表
 * @author liuchunyan
 * @date 2017-05-08
 * @version 1.0
 */
@Controller
@RequestMapping("/h5/cashier/receiver")
public class CashierController {
	private static Logger logger = LoggerFactory.getLogger(CashierController.class);

	//查询第三方网站用户 ,查询用户详情接口
	@Resource
	private UserServiceRemote userServiceRemote_sp;
	
	//查询第三方网站用户 ,查询用户详情接口
	@Resource
	private WeixinService weixinService;
	
	/**
	 * desc:收银员列表接口
	 * 
	 * @param reqMessage
	 * @return ResMessage
	 * @throws 
	 * 	 */
	@RequestMapping(value="/getcashierList",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String getcashierList(HttpServletRequest request, HttpServletResponse response) throws Exception{		
		logger.info("收银员列表接口 开始");
		String storeId = request.getParameter("storeId"); //店铺编号
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{
			//用户列表查询接口
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			reqMessage.getReqMap().put("merFlag", storeId);//商户标识
			reqMessage.getReqMap().put("rank", "1");//操作员
			reqMessage.getReqMap().put(XmlData.STATE, "0");//正常
			reqMessage.getReqMap().put("currentPage", String.valueOf(1));
			reqMessage.getReqMap().put("pageSize", String.valueOf(100));
			logger.info("用户列表查询接口 ：reqMessage=" + reqMessage);
			ResMessage resMessage = userServiceRemote_sp.queryList(reqMessage);
			List<Map<String, Object>> resultList = (List<Map<String, Object>>)resMessage.getResMap().get(XmlData.RESULT_LIST);
				
			//已邀请集合
			List<Map<String, Object>> userInvitedList = new ArrayList<Map<String, Object>>();
			//未邀请集合
			List<Map<String, Object>> userNoInviteList = new ArrayList<Map<String, Object>>();
			if(resultList != null && resultList.size() > 0){
				for(Map<String, Object> objMap : resultList){
					//查询第三方网站用户接口
					ReqMessage reqMess = ReqMessageUtil.makeSpReq();
					reqMess.getReqMap().put("userId", objMap.get("userId").toString());
					logger.info("查询第三方网站用户接口 ：reqMess = " + reqMess);
					ResMessage resMess = userServiceRemote_sp.queryUserBind(reqMess);
					logger.info("查询第三方网站用户接口 ：resMess = " + resMess);
					
					Map<String, Object> addMap = new HashMap<String, Object>();
					addMap.put("userId", objMap.get("userId"));
					addMap.put("name", objMap.get("name"));
					addMap.put("isRefund", objMap.get("isRefund"));
					addMap.put("telephoneNo", objMap.get("telephoneNo"));
					
					if(resMess.getRetCode().equals(ConstEC.SUCCESS)){
						userInvitedList.add(addMap);
					}else{
						userNoInviteList.add(addMap);
					}
				}
			}
			
			resultMap.put("retCode", RetCode.SUCCESS);
			resultMap.put("retMsg", "获取收银员列表成功！");
			resultMap.put("userRefundList", userInvitedList);//已邀请
			resultMap.put("userInviteList", userNoInviteList);//未邀请
			logger.info("收银员列表 ：resultMap = " + resultMap);
			return JSONObject.fromObject(resultMap).toString();
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("获取收银员列表失败",e);
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "获取收银员列表失败");
			return JSONObject.fromObject(resultMap).toString();
		}
	}
    
	/**
	 * desc:添加收银员接口
	 * 
	 * @param reqMessage
	 * @return ResMessage
	 * @throws 
	 * 	 */
	@RequestMapping(value="/addCashier",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String addCashier(HttpServletRequest request, HttpServletResponse response) throws Exception{		
		logger.info("添加收银员接口 开始");
		String openid = "";
		if(request.getSession().getAttribute("openid") != null){
			openid = request.getSession().getAttribute("openid").toString();//获取openid
		}
		String storeId = request.getParameter("storeId"); //店铺编号
		String name = request.getParameter("name"); //收银员姓名
		String telephoneNo = request.getParameter("telephoneNo"); //收银员手机号码
		String isRefund = request.getParameter("isRefund"); //退款权限
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		//用户列表查询
		ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
		reqMessage.getReqMap().put(XmlData.MERFLAG, storeId);//商户标识
		reqMessage.getReqMap().put(XmlData.STATE, "0");//正常
		reqMessage.getReqMap().put(XmlData.NAME, name);//收银员姓名
		reqMessage.getReqMap().put(XmlData.TELEPHONENO, null);//收银员手机号码
		reqMessage.getReqMap().put(XmlData.CURRENT_PAGE, String.valueOf(1));
		reqMessage.getReqMap().put(XmlData.PAGE_SIZE, String.valueOf(10));
		logger.info("用户列表查询接口 ：reqMessage=" + reqMessage);
		ResMessage resMessage = userServiceRemote_sp.queryList(reqMessage);
		logger.info("用户列表查询接口结束 ：resMessage=" + resMessage);
		Integer totalSize = (Integer)resMessage.getResMap().get("totalSize");
		
		if(totalSize == 0){
			reqMessage.getReqMap().put(XmlData.NAME, null);//收银员姓名
			reqMessage.getReqMap().put(XmlData.TELEPHONENO, telephoneNo);//收银员手机号码
			logger.info("用户列表查询接口 ：reqMessage=" + reqMessage);
			resMessage = userServiceRemote_sp.queryList(reqMessage);
			logger.info("用户列表查询接口结束 ：resMessage=" + resMessage);
			totalSize = (Integer)resMessage.getResMap().get("totalSize");
	    }
		if(totalSize > 0){
			List<Map<String, Object>> resultList3 = (List<Map<String, Object>>)resMessage.getResMap().get(XmlData.RESULT_LIST);
			Map<String, Object> map = resultList3.get(0);
			String rank = map.get("rank").toString();
			if(rank.equals("1")){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", "您已在该店铺下增加过此收银员！");
				logger.info("您["+name+"]已在该店铺下增加过此收银员！");
			}else{
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", "您已是此店铺收款人，不能再次添加自己为收银员！");
				logger.info("您["+name+"]已是此店铺收款人，不能再次添加自己为收银员！");
			}
			return JSONObject.fromObject(resultMap).toString(); 
		}
		
		//根据opendi查询第三方网站用户的用户编号
		ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		reqMess.getReqMap().put("externaluserId", openid);
		logger.info("查询第三方网站用户接口 ：externaluserId=" + openid);
		ResMessage resMess = userServiceRemote_sp.queryUserBind(reqMess);
		if(resMess.getResMap().get("userId") == null){//未取到用户编号
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "未获取到用户编号！");
			logger.info("查询第三方网站用户接口 ：未获取到用户编号");
			return JSONObject.fromObject(resultMap).toString();
		}
		String userId = "";
		if(resMess.getResMap().get("userId") != null){
			userId = resMess.getResMap().get("userId").toString();//用户编号
		}
		
		//查询用户详情接口
		ReqMessage reqM = ReqMessageUtil.makeSpReq();
		reqM.getReqMap().put("userId", userId);
		logger.info("查询用户详情接口 ：userId=" + userId);
		ResMessage resM = userServiceRemote_sp.getUserByIdSaaS(reqM);
		Map map = (Map)resM.getValue(XmlData.MER_USER);
		userId = map.get("userId").toString();
		
		if(StringUtil.isEmpty(userId)){//未取到用户详情
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "未获取到用户详情！");
			logger.info("查询用户详情接口 ：未获取到用户详情");
			return JSONObject.fromObject(resultMap).toString();
		}
		if(!"0".equals(map.get("state").toString())){//非正常
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "用户不可用！");
			logger.info("查询用户详情接口 ：用户不可用");
			return JSONObject.fromObject(resultMap).toString();
		}
		
		//添加操作员
		try{
			Calendar calendar = Calendar.getInstance();
			Long timeInMillis = calendar.getTimeInMillis();
			ReqMessage addReqMessage = ReqMessageUtil.makeSpReq();
			addReqMessage.getReqMap().put("merId", storeId);
			addReqMessage.getReqMap().put("telephoneNo", telephoneNo);
			addReqMessage.getReqMap().put("logname", "saaswx" + timeInMillis + getFourRandom());
			addReqMessage.getReqMap().put("name", name);
			addReqMessage.getReqMap().put("creator", userId);
			addReqMessage.getReqMap().put("isRefund", isRefund);
			logger.info("添加收银员接口 ：reqMessage=" + addReqMessage);
			ResMessage addResMessage = userServiceRemote_sp.addOperUser(addReqMessage);
			if(!addResMessage.getRetCode().equals(RetCode.SUCCESS)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", "添加收银员失败！");
				logger.info("添加收银员接口 ：添加收银员失败");
				return JSONObject.fromObject(resultMap).toString();
			}
			
			resultMap.put("retCode", RetCode.SUCCESS);
			resultMap.put("name", name);
			resultMap.put("userId", addResMessage.getValue(XmlData.USERID));
			resultMap.put("retMsg", "添加收银员成功！");
			return JSONObject.fromObject(resultMap).toString();
			
		} catch (Exception e) {
			logger.info("添加收银员失败",e);
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "添加收银员失败");
		}
		
		return JSONObject.fromObject(resultMap).toString();
	}
	
	
	/**
	 * desc:删除收银员接口
	 * @param reqMessage
	 * @return ResMessage
	 * @throws 
	 */
	@RequestMapping(value="/delCashier",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String delCashier(String userId,HttpServletRequest request, HttpServletResponse response) throws Exception{		
		logger.info("删除收银员接口=====开始=====>>>>>>>|CashierController|delCashier");
		ResMessage resMessage = new ResMessage();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		//判断userId是否为null
		if(StringUtil.isEmpty(userId)){
			resultMap.put("retCode", RetCode.FAIL);
			resultMap.put("retMsg", "userId传值失败！");
			logger.info("+++++++userId传值失败！++++++++++");
			return JSONObject.fromObject(resultMap).toString();
		}
		try{
			//根据userId查询第三方网站用户的openId
			ReqMessage req1 = ReqMessageUtil.makeSpReq();
			req1.getReqMap().put("userId", userId);
			logger.info("查询第三方网站用户接口开始 ：【1】【1】【1】【1】入参【userId】=" + userId);
		    ResMessage res1 = userServiceRemote_sp.queryUserBind(req1);
			logger.info("查询第三方网站用户接口结束 ：【1】【1】【1】【1】resMessage=" + res1.getRetCode());
			//第三方网站有数据
			if(res1.getRetCode().equals(RetCode.SUCCESS)){
				String openid = res1.getValue("externalUserId").toString();
				//解绑第三方网站用户
				ReqMessage req2 = ReqMessageUtil.makeSpReq();
				req2.getReqMap().put("userId", userId);
				req2.getReqMap().put("state","4");
				req2.getReqMap().put("externaluserId",openid);
				logger.info("解绑第三方网站用户接口开始 ：【2】【2】【2】【2】入参【req2】="+ req2);
			    ResMessage res2 = userServiceRemote_sp.unBindUser(req2);
				logger.info("解绑第三方网站用户接口结束 ：【2】【2】【2】【2】resMessage=" + res2);
				
				if(!res2.getRetCode().equals(RetCode.SUCCESS)){
					resultMap.put("retCode", RetCode.FAIL);
					resultMap.put("retMsg", "解绑失败！");
					logger.info("解绑第三方网站用户接口失败 : 【res2】【失败】"+res2.getRetMsg());
					return JSONObject.fromObject(resultMap).toString();
				}
				//给用户打标签
				logger.info("微信公众号|移动用户分组接口=====开始=====+++++");
				boolean addUserGroup = weixinService.addUserGroup(openid, 0);
				logger.info("微信公众号|移动用户分组接口=====结束======+addUserGroup+++++"+addUserGroup);
				if(addUserGroup==false){
					resultMap.put("retCode", RetCode.FAIL);
					resultMap.put("retMsg", "公众号未成功改成默认标签！！");
					logger.info("+++++++++公众号未成功改成默认标签！+++++++");
					//return JSONObject.fromObject(resultMap).toString();
				}
			//第三方网站查询异常	
			}else if(!res1.getRetCode().equals(ConstEC.NO_DATA)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", "解绑失败！");
				logger.info("查询第三方网站用户接口失败 : "+res1.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
				
			}
			//修改操作员接口
			ReqMessage req3 = ReqMessageUtil.makeSpReq();
			req3.getReqMap().put("userId",userId);
			req3.getReqMap().put("state", "1");
			logger.info("修改操作员接口开始 ：【3】【3】【3】【3】【userId】=" + userId+"【state】"+ 1);
			ResMessage res3 = userServiceRemote_sp.modifyUserById(req3);
			logger.info("修改操作员接口结束 ：【3】【3】【3】【3】resMessage=" + res3);
			if(!res3.getRetCode().equals(RetCode.SUCCESS)){
				resultMap.put("retCode", RetCode.FAIL);
				resultMap.put("retMsg", "修改操作员接口失败！");
				logger.info("修改操作员接口接口失败 ：【res3】【失败】" +res3.getRetMsg());
				return JSONObject.fromObject(resultMap).toString();
			}
			resultMap.put("retCode",RetCode.SUCCESS);
			resultMap.put("retMsg", "删除收银员成功");
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("删除收银员接口异常<<<<<<<<<<<" +e);
			resultMap.put("retCode",RetCode.UNKNOWN);
			resultMap.put("retMsg", "删除收银员接口异常");
		}
		logger.info("删除接口结束======结束====>>>>>>>|CashierController|delCashier");
		return JSONObject.fromObject(resultMap).toString();
	}
	
	/**
	 * desc:邀请收银员接口
	 * @param reqMessage
	 * @return ResMessage
	 * @throws 
	 */
	@RequestMapping(value="/inviteCashier",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String inviteCashier(String userId) throws Exception{		
		//String userId="2000001137";
		logger.info("邀请收银员接口开始==========>>>>>|CashierController|inviteCashier");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		try{
			String ticket = RedisUtil.get(CacheConsts.WX+"ticketQrCode"+userId);
			logger.info("从redis中获取ticket=========="+ticket);
			if(StringUtil.isEmpty(ticket)){
				logger.info("重新获取ticket=========="+ticket);
				//二维码有效期
				String expireSeconds="86400";
				//创建临时二维码
				ticket = weixinService.getTicketQrCode(expireSeconds,Integer.parseInt(userId));
				if(StringUtil.isEmpty(ticket)){
					resultMap.put("retCode", RetCode.FAIL);
					resultMap.put("retMsg", "二维码未生成！");
					logger.info("邀请收银员接口 失败：二维码未生成");
					return JSONObject.fromObject(resultMap).toString();
				}
				RedisUtil.set(CacheConsts.WX+"ticketQrCode"+userId,86000,ticket);
			}
			resultMap.put("retCode", RetCode.SUCCESS);
			resultMap.put("retMsg", "二维码生成成功！");
			resultMap.put("ticket", ticket);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("邀请收银员接口异常<<<<<<<<<<<<" +e);
			resultMap.put("retCode",RetCode.UNKNOWN);
			resultMap.put("retMsg", "邀请收银员接口异常！");
		}
		logger.info("邀请收银员接口结束=========>>>>>>>|CashierController|inviteCashier");
		return JSONObject.fromObject(resultMap).toString();
	}
	
	/**
     * 产生4位随机数(0000-9999)
     * @return 4位随机数
    */
    private String getFourRandom(){
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if(randLength<4){
          for(int i=1; i<=4-randLength; i++)
              fourRandom = "0" + fourRandom  ;
      }
        return fourRandom;
    } 
}